package common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.SystemPropsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author gitama
 * @version 1.0
 * @date 2021/7/20 5:45 下午
 */
public class PropertiesUtil {

    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    private static Properties props;

    static {
        loadProps();
    }

    private synchronized static void loadProps() {
        props = new Properties();
        InputStream in = null;
        try {
            String filePath = SystemPropsUtil.get("user.dir") + File.separator + "config.properties";
            logger.info("开始加载properties文件内容:" + filePath);
            if (FileUtil.exist(filePath)) {
                in = FileUtil.getInputStream(filePath);
            } else {
                in = PropertiesUtil.class.getClassLoader().getResourceAsStream("config.properties");
            }
            props.load(in);
        } catch (FileNotFoundException e) {
            logger.error("jdbc.properties文件未找到");
        } catch (IOException e) {
            logger.error("出现IOException");
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("vas.properties文件流关闭出现异常");
            }
        }
        logger.info("加载properties文件内容完成...........");
    }

    public static String getProperty(String key) {
        if (props == null) {
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if (props == null) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }

}
